package 抽象数据类型;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @description: 实现滑动窗口
 * @author: ywk
 * @date: 2021-03-02
 */
public class 单调队列 {
    class MonotonicQueue {
        private Deque<Integer> data;

        public MonotonicQueue() {
            data = new LinkedList<>();
        }

        public void push(int n) {
            while (!data.isEmpty() && data.peekLast() < n) {
                data.removeLast();
            }
            data.offerLast(n);
        }

        public int max() {
            return data.peekFirst();
        }

        public void pop(int n) {
            if (!data.isEmpty() && data.peekFirst() == n) {
                data.removeFirst();
            }
        }
    }

    public int[] maxSlidingWindow(int[] nums, int k) {
        MonotonicQueue queue = new MonotonicQueue();
        int[] res = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (i < k - 1) {
                queue.push(nums[i]);
            } else {
                queue.push(nums[i]);
                res[i] = queue.max();
                queue.pop(nums[i - k + 1]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        单调队列 que = new 单调队列();
        int[] ints = que.maxSlidingWindow(new int[]{2, 5, 4, 3, 2, 1, 0}, 3);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }
}